package com.hrz.lib.rxmvpdemo2.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hrz.lib.rxmvpdemo2.BaseModule;
import com.hrz.lib.rxmvpdemo2.R;
import com.hrz.lib.rxmvpdemo2.contract.main.DaggerMainComponent;
import com.hrz.lib.rxmvpdemo2.contract.main.MainContract;
import com.hrz.lib.rxmvpdemo2.contract.main.MainPresenter;
import com.rxmvp.baselibrary.App;
import com.rxmvp.baselibrary.AppManager;
import com.rxmvp.baselibrary.R2;
import com.rxmvp.baselibrary.base.dagger.ActivityModule;
import com.rxmvp.baselibrary.base.mvp.BasePresenterActivity;
import com.rxmvp.baselibrary.utils.LogUtil;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 主页面
 * <p>
 * 作者： huangRZ on 2017/1/21. 15:04
 * 邮箱：917647409@qq.com
 */
public class FirstActivity extends BasePresenterActivity<MainPresenter> implements MainContract.IView, View.OnClickListener {

    @BindView(R2.id.tv_json)
    TextView tv;
    @BindView(R2.id.progress)
    ProgressBar progressBar;
    @BindView(R2.id.btn_get_data)
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);

        DaggerMainComponent.builder()
                .activityModule(new ActivityModule(this, this))
                .baseModule(new BaseModule())
                .globalComponent(App.getGlobalComponent())
                .build().inject(this);

        //利用leakCanary检测是否发生内存泄漏
        App.getRefWatcher(this).watch(this);
    }

    @OnClick({R2.id.btn_get_data, R2.id.btn_to_second, R2.id.btn_cancel})
    public void onClick(View view) {
        LogUtil.e("" + view.getId());
        if (view.getId() == R.id.btn_get_data) {
            //获取网络数据
            mPresenter.loadData();
        } else if (view.getId() == R.id.btn_to_second) {
            //跳转到second页面
            startActivity(new Intent(this, SecondActivity.class));
        } else if (R.id.btn_cancel == view.getId()) {
            //取消异步操作
            mPresenter.cancelSubscription();
        }
    }

    @Override
    public void setText(String text) {
        tv.setText(text);
    }

    @Override
    public void showPB() {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void hidePB() {
        progressBar.setVisibility(View.GONE);
    }


    private boolean flag = false;

    @Override
    public void onBackPressed() {
        if (!flag) {
            flag = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    flag = false;
                }
            }, 2000);
            showShortToast("再按一次退出应用");
        } else {
            //退出应用
            AppManager.finishAllActivity();
        }
    }
}
